package cn.yj.quartz;

import cn.yj.annotation.pagehelper.PageBaseController;
import cn.yj.common.Enums;
import cn.yj.commons.StringPools;
import cn.yj.entity.R;
import cn.yj.quartz.service.QuartzJobService;
import cn.yj.syslog.common.LogType;
import cn.yj.syslog.common.OperateLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.quartz.SchedulerException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author 永健
 * @since 2022-01-14 20:56
 */
@RequestMapping("/quartz")
@RestController
public class QuartzController implements PageBaseController<QuartzJob> {


    @Resource
    private QuartzJobService jobService;

    @GetMapping("/list")
    @RequiresPermissions("quartz:list")
    public R pageList(QuartzJob quartzJob) {
        return R.success(jobService.selectJobList(page(), quartzJob));
    }


    @OperateLog(describe = "增加定时任务", type = LogType.INSERT)
    @PostMapping("/save")
    @RequiresPermissions("quartz:add")
    public R save(@RequestBody QuartzJob quartzJob) throws SchedulerException {
        return R.success(jobService.insertJob(quartzJob));
    }

    @OperateLog(describe = "修改定时任务", type = LogType.UPDATE)
    @PutMapping("/update")
    @RequiresPermissions("quartz:update")
    public R update(@RequestBody QuartzJob quartzJob) throws SchedulerException {
        return R.success(jobService.updateJob(quartzJob));
    }

    @RequiresPermissions("quartz:del")
    @OperateLog(describe = "删除定时任务", type = LogType.DELETE)
    @DeleteMapping("/remove/{ids}")
    public R update(@PathVariable Long[] ids) throws SchedulerException {
        jobService.deleteJobByIds(ids);
        return R.success();
    }

    @RequiresPermissions("quartz:pause")
    @PostMapping("/pause/{jobId}")
    @OperateLog(describe = "停止任务执行", type = LogType.OTHER)
    public R pause(@PathVariable Long jobId) throws SchedulerException {
        return jobService.pauseJob(jobId)?R.success():R.error();
    }

    @RequiresPermissions("quartz:resumeJob")
    @PostMapping("/resumeJob/{jobId}")
    @OperateLog(describe = "开启任务执行", type = LogType.OTHER)
    public R resumeJob(@PathVariable Long jobId) throws SchedulerException {
        return jobService.resumeJob(jobId)> Enums.Common.ZERO?R.success():R.error();
    }

    @RequiresPermissions("quartz:run")
    @PostMapping("/run/{jobId}")
    @OperateLog(describe = "执行一次任务", type = LogType.OTHER)
    public R run(@PathVariable Long jobId) throws SchedulerException {
        return jobService.runJob(jobId)?R.success():R.error();
    }
}
